﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
using System.IO;
using WindowsFormsApplication1.BLL;
using Millionaire;
using System.Threading;
using System.ServiceModel;
using System.ServiceModel.Description;
using demobackground.LuuDiemService1;
using Microsoft.Devices;
using Microsoft.Phone.Net.NetworkInformation;


namespace demobackground
{
    public partial class secondpage : PhoneApplicationPage
    {
        List<int> listDiem;
        List<int> listLV;
        NguoiChoiBLL ncBLL;
        NguoiChoi nc;
        private int soThuTu = 1;
        private CauHoiBLL cauHoiBLL;
        private LuotChoiBLL luotChoiBLL;
        private ChiTietLuotChoiBLL chiTietBLL;
        private LuotChoi lc;
        private string dapAn = "";
        private int currCauHoi;
        private bool tatCaLV = false;
        private bool tieng;
        LinearGradientBrush gb;
        Storyboard story;
        public secondpage()
        {
            InitializeComponent();
            listLV = new List<int>();
            ncBLL = new NguoiChoiBLL();
            cauHoiBLL = new CauHoiBLL();
            luotChoiBLL = new LuotChoiBLL();
            chiTietBLL = new ChiTietLuotChoiBLL();
            listDiem = new List<int>(){
                100,200,300,500,1000,2000,3600,6000,9000,15000,25000,35000,50000,80000,120000
            };
            txtSTT.Text = "0";
            App a = App.Current as App;
            tieng = a.tieng;
            if (tieng == false)
            {
                demoSound.Source = null;
            }
            gb = new LinearGradientBrush();
            gb.StartPoint = new System.Windows.Point(0, 0);
            gb.EndPoint = new System.Windows.Point(1, 0);
            gb.GradientStops.Add(new GradientStop() { Color = System.Windows.Media.Color.FromArgb(255, 0, 0, 0), Offset = 0 });
            gb.GradientStops.Add(new GradientStop() { Color = System.Windows.Media.Color.FromArgb(255, 0, 255, 25), Offset = 0.5 });
            gb.GradientStops.Add(new GradientStop() { Color = System.Windows.Media.Color.FromArgb(255, 0, 0, 0), Offset = 1 });
        }

     

        private void DisplayCauHoi()
        {
            txtA.Opacity = 1;
            txtB.Opacity = 1;
            txtC.Opacity = 1;
            txtD.Opacity = 1;
            borderDiem.SetValue(Grid.RowProperty, -soThuTu + 15);
          
          
                demoSound.Play();
          
            CauHoi ch;
            if (tatCaLV)
                ch = cauHoiBLL.RandomMD(soThuTu);
            else
                ch = cauHoiBLL.RandomNhieuLV(listLV, soThuTu);
            if (ch == null)
            {
                ch = cauHoiBLL.RandomMD(soThuTu);
                //MessageBox.Show("Hết câu hỏi");
                //return;
            }
            if (ch.CauHoi1.Contains('#'))
            {
                string[] arr = ch.CauHoi1.Split('#');
                txtCauHoi.Text = arr[0];
                imageCauHoi.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("image/" + arr[1]);
            }
            else 
            { txtCauHoi.Text = ch.CauHoi1;
            imageCauHoi.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("image/wwtbam_logo1.png"); 
            }

            currCauHoi = ch.MaCauHoi;
            
            txtA.Text = "A. " + ch.CauA;
            txtB.Text = "B. " + ch.CauB;
            txtC.Text = "C. " + ch.CauC;
            txtD.Text = "D. " + ch.CauD;
            dapAn = ch.DapAn;
            ChiTietLuotChoi chitiet = new ChiTietLuotChoi()
            {
                MaCauHoi = ch.MaCauHoi,
                MaLuotChoi = lc.MaLuotChoi,
                STTCauHoi = soThuTu
            };
            chiTietBLL.AddNew(chitiet);
            //SetEnable();
        }

      
        
        #region Sound
        private void demoSound_MediaOpened(object sender, RoutedEventArgs e)
        {
            //MediaElement m = (MediaElement)sender;
            //m.Play();
            demoSound.Play();
        }

        //private void demoSound_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        //{
        //  //  MessageBox.Show("sai");
        //}

        private void demoSound_MediaEnded(object sender, RoutedEventArgs e)
        {
            demoSound.Play();
        }
#endregion 


        private void btnDoiCauHoi_Click(object sender, RoutedEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            SoundController.PlaySound("Sound/Refresh.wav",tieng,1000);
            CauHoi ch;
            if (tatCaLV)
                ch = cauHoiBLL.DoiCauHoi(soThuTu, currCauHoi);
            else
                ch = cauHoiBLL.DoiCauHoi(listLV, soThuTu, currCauHoi);
            if (ch == null)
            {
                ch = cauHoiBLL.RandomMD(soThuTu);
            }
            if (ch.CauHoi1.Contains('#'))
            {
                string[] arr = ch.CauHoi1.Split('#');
                txtCauHoi.Text = arr[0];
                imageCauHoi.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("image/" + arr[1]);
            }
            else
            {
                txtCauHoi.Text = ch.CauHoi1;
                imageCauHoi.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("image/wwtbam_logo1.png");
            }

            txtCauHoi.Text = ch.CauHoi1;
            txtA.Text = "A. " + ch.CauA;
            txtB.Text = "B. " + ch.CauB;
            txtC.Text = "C. " + ch.CauC;
            txtD.Text = "D. " + ch.CauD;
            dapAn = ch.DapAn;
            ChiTietLuotChoi chitiet = chiTietBLL.GetByCauHoiLuotChoi(currCauHoi, lc.MaLuotChoi);
            chitiet.MaCauHoi = ch.MaCauHoi;
            chiTietBLL.Update(chitiet);
            currCauHoi = ch.MaCauHoi;
            chiTietBLL.AddNew(chitiet);
            btnDoiCauHoi.IsEnabled = false;
        }



        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            App a = Application.Current as App;
            listLV = a.listLV;           
            nc = new NguoiChoi();
            nc = ncBLL.GetByID(a.IdNguoiChoi);
            if (listLV == null || listLV.Contains(0)|| listLV.Count == 0)
                tatCaLV = true;
            lc = new LuotChoi()
            {
                MaNguoiChoi = nc.MaNguoiChoi,
                Ngay = DateTime.Now
            };
            luotChoiBLL.AddNew(lc);
            DisplayCauHoi();
        }

        private void btn50_Click(object sender, RoutedEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            txtA.Opacity = 0;
            txtB.Opacity = 0;
            txtC.Opacity = 0;
            txtD.Opacity = 0;
            Random r = new Random();
            int[] arr;
            int select = 0;
            if (dapAn == "A")
            {
                arr = new int[3] {2,3,4 };
                select = arr[r.Next(1, 3)];
                txtA.Opacity = 1;

            }
            if (dapAn == "B")
            {
                arr = new int[3] { 1, 3, 4 };
                select = arr[r.Next(1, 3)];
                txtB.Opacity = 1 ;
            }
            if (dapAn == "C")
            {
                arr = new int[3] {1, 2, 4 };
                select = arr[r.Next(1, 3)];
                txtC.Opacity = 1;
            }
            if (dapAn == "D")
            {
                arr = new int[3] { 1,2, 3};
                select = arr[r.Next(1, 3)];
                txtD.Opacity = 1;
            }
            if (select == 1)
            {
                txtA.Opacity = 1;
            }
            else if (select == 2)
            {
                txtB.Opacity = 1;
            }
            else if (select == 3)
            {
                txtC.Opacity = 1;
            }
            else
            {
                txtD.Opacity = 1;
            }
            btn50.IsEnabled = false;
        }

        
        private void btnDungChoi_Click(object sender, RoutedEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            if((MessageBox.Show("Bạn có chắc muốn dừng cuộc chơi?","",MessageBoxButton.OKCancel) == MessageBoxResult.OK))
            {
                int diem = 0;
                if(soThuTu > 1)
                    diem = listDiem[soThuTu - 1];
                MessageBox.Show("Bạn đạt được " + diem + " điểm");
                lc.TongDiem = diem;
                luotChoiBLL.Update(lc);
                LuuDiem(diem);              
                NavigationService.GoBack();
            }

        }

        private void txtA_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
          

            demoSound.Stop();
            if (dapAn == "A")
            {
                HieuUngTraLoi(true, gridA);
                SoundController.PlaySound("Sound/WinSound.wav", tieng, 4000);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(4000) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {
                    if (soThuTu == 15)
                    {
                        lc.TongDiem = 120000;
                        luotChoiBLL.Update(lc);
                        MessageBox.Show("Bạn đạt được " + lc.TongDiem + " điểm");
                        MessageBox.Show("Xin chúc mừng!Bạn đã là triệu phú");
                        LuuDiem(lc.TongDiem.Value);
                        NavigationService.GoBack();
                    }
                    else
                    {
                        txtSTT.Text = listDiem[soThuTu - 1].ToString();
                        soThuTu++;
                        DisplayCauHoi();
                    }

                };
            }
            else
            { HieuUngTraLoi(false, gridA);
                SoundController.PlaySound("Sound/FailSound.wav", tieng, 3500);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(3500) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {

                    int diem = 0;
                    if (soThuTu < 6)
                    {
                        diem = 0;
                    }
                    else if (soThuTu < 11)
                    {
                        diem = 1000;
                    }
                    else if (soThuTu < 16)
                    {
                        diem = 15000;
                    }
                    MessageBox.Show("Trả lời sai. Đáp án đúng là : " + dapAn);
                    MessageBox.Show("Bạn đạt được " + diem + " điểm");
                    lc.TongDiem = diem;
                    luotChoiBLL.Update(lc);
                    LuuDiem(diem);
                    NavigationService.GoBack();
                };
            }
        }

        private void LuuDiem(int diem)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                ServiceLuuDiemClient client = new ServiceLuuDiemClient();
                KetQua kq = new KetQua() { TenNguoiChoi = nc.HoTen, Diem = diem };
                client.SetDataAsync(kq);
            }
        }

        private void txtB_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            demoSound.Stop();
            if (dapAn == "B")
            { HieuUngTraLoi(true, gridB);
                SoundController.PlaySound("Sound/WinSound.wav", tieng, 4000);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(4000) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {
                    if (soThuTu == 15)
                    {
                        lc.TongDiem = 120000;
                        luotChoiBLL.Update(lc);
                        MessageBox.Show("Bạn đạt được " + lc.TongDiem + " điểm");
                        MessageBox.Show("Xin chúc mừng!Bạn đã là triệu phú");
                        LuuDiem(lc.TongDiem.Value);
                        NavigationService.GoBack();
                    }
                    else
                    {
                        txtSTT.Text = listDiem[soThuTu - 1].ToString();
                        soThuTu++;
                        DisplayCauHoi();
                    }

                };
            }
            else
            {HieuUngTraLoi(false, gridB);
                SoundController.PlaySound("Sound/FailSound.wav", tieng, 3500);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(3500) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {

                    int diem = 0;
                    if (soThuTu < 6)
                    {
                        diem = 0;
                    }
                    else if (soThuTu < 11)
                    {
                        diem = 1000;
                    }
                    else if (soThuTu < 16)
                    {
                        diem = 15000;
                    }
                    MessageBox.Show("Trả lời sai. Đáp án đúng là : " + dapAn);
                    MessageBox.Show("Bạn đạt được " + diem + " điểm");
                    lc.TongDiem = diem;
                    luotChoiBLL.Update(lc);
                    LuuDiem(diem);
                    NavigationService.GoBack();
                };
            }
        }

        private void txtC_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            demoSound.Stop();
            if (dapAn == "C")
            {HieuUngTraLoi(true, gridC);
                SoundController.PlaySound("Sound/WinSound.wav", tieng, 4000);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(4000) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {
                    if (soThuTu == 15)
                    {
                        lc.TongDiem = 120000;
                        luotChoiBLL.Update(lc);
                        MessageBox.Show("Bạn đạt được " + lc.TongDiem + " điểm");
                        MessageBox.Show("Xin chúc mừng!Bạn đã là triệu phú");
                        LuuDiem(lc.TongDiem.Value);
                        NavigationService.GoBack();
                    }
                    else
                    {
                        txtSTT.Text = listDiem[soThuTu - 1].ToString();
                        soThuTu++;
                        DisplayCauHoi();
                    }

                };
            }
            else
            {HieuUngTraLoi(false, gridC);
                SoundController.PlaySound("Sound/FailSound.wav", tieng, 3500);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(3500) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {

                    int diem = 0;
                    if (soThuTu < 6)
                    {
                        diem = 0;
                    }
                    else if (soThuTu < 11)
                    {
                        diem = 1000;
                    }
                    else if (soThuTu < 16)
                    {
                        diem = 15000;
                    }
                    MessageBox.Show("Trả lời sai. Đáp án đúng là : " + dapAn);
                    MessageBox.Show("Bạn đạt được " + diem + " điểm");
                    lc.TongDiem = diem;
                    luotChoiBLL.Update(lc);
                    LuuDiem(diem);
                    NavigationService.GoBack();
                };
            }
        }

        private void txtD_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VibrateController vc = VibrateController.Default;
            vc.Start(TimeSpan.FromSeconds(0.1));
            demoSound.Stop();
            if (dapAn == "D")
            {HieuUngTraLoi(true, gridD);
                SoundController.PlaySound("Sound/WinSound.wav", tieng, 4000);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(4000) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {
                    if (soThuTu == 15)
                    {
                        lc.TongDiem = 120000;
                        luotChoiBLL.Update(lc);
                        MessageBox.Show("Bạn đạt được " + lc.TongDiem + " điểm");
                        MessageBox.Show("Xin chúc mừng!Bạn đã là triệu phú");
                        LuuDiem(lc.TongDiem.Value);
                        NavigationService.GoBack();
                    }
                    else
                    {
                        txtSTT.Text = listDiem[soThuTu - 1].ToString();
                        soThuTu++;
                        DisplayCauHoi();
                    }
                   
                };
               
            }
            else
            {
                HieuUngTraLoi(false, gridD);
                SoundController.PlaySound("Sound/FailSound.wav", tieng, 3500);
                Storyboard sb = new Storyboard() { Duration = TimeSpan.FromMilliseconds(3500) };
                sb.Begin();
                sb.Completed += (ds, de) =>
                {

                    int diem = 0;
                    if (soThuTu < 6)
                    {
                        diem = 0;
                    }
                    else if (soThuTu < 11)
                    {
                        diem = 1000;
                    }
                    else if (soThuTu < 16)
                    {
                        diem = 15000;
                    }
                    MessageBox.Show("Trả lời sai. Đáp án đúng là : " + dapAn);
                    MessageBox.Show("Bạn đạt được " + diem + " điểm");
                    lc.TongDiem = diem;
                    luotChoiBLL.Update(lc);
                    LuuDiem(diem);
                    NavigationService.GoBack();
                };
            }
        }

        void HieuUngTraLoi(bool dapan,Grid g)
        {
            g.Background = gb;
            SetBackground(g);
            ColorAnimation ca = new ColorAnimation()
            {
                From = Colors.Black,
                To = dapan? Colors.Green: Colors.Red,               
                Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                AutoReverse = true,
                RepeatBehavior = new RepeatBehavior(3)
            };

            Storyboard.SetTarget(ca, gb);
            Storyboard.SetTargetProperty(ca, new PropertyPath("GradientStops[1].Color"));
            story = new Storyboard();
            story.Children.Add(ca);
            story.Begin();
        }

        private void SetBackground(Grid g)
        {
            if (g == gridA)
            {
                gridB.Background = new SolidColorBrush( Colors.Black);
                gridC.Background = new SolidColorBrush(Colors.Black);
                gridD.Background = new SolidColorBrush(Colors.Black);
            }
            else if(g == gridB)
            {
                gridA.Background = new SolidColorBrush(Colors.Black);
                gridC.Background = new SolidColorBrush(Colors.Black);
                gridD.Background = new SolidColorBrush(Colors.Black);
            }
            else if (g == gridC)
            {
                gridA.Background = new SolidColorBrush(Colors.Black);
                gridB.Background = new SolidColorBrush(Colors.Black);
                gridD.Background = new SolidColorBrush(Colors.Black);
            }
            else if (g == gridD)
            {
                gridA.Background = new SolidColorBrush(Colors.Black);
                gridC.Background = new SolidColorBrush(Colors.Black);
                gridB.Background = new SolidColorBrush(Colors.Black);
            }
        }
        
    }
}